// 教师管理主组件
import { useModel } from 'umi';
import { PageContainer } from '@ant-design/pro-components';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import ImageUploader from '@/components/ImageUploader';
import {
    Card, Typography, Input, Select, DatePicker, Button, Form, Row, Col,
    Tabs, Space, Table, message, Image, Popconfirm, Modal, Radio
} from 'antd';
import {
    SearchOutlined, ReloadOutlined, PlusOutlined, EditOutlined,
    DeleteOutlined, RedoOutlined, CheckOutlined, CloseOutlined
} from '@ant-design/icons';
import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useListApi, useDeleteApi, useAddApi } from '@/api/teacher/index';
import styles from './index.module.css';
import type { ColumnsType, TableProps, TablePaginationConfig } from 'antd/es/table';
import { handleNumberInput, handlePasswordInput, handleTextOnlyInput } from '@/components/business/index';

// 扩展dayjs功能
dayjs.extend(customParseFormat);

// 常量定义 
const { Title } = Typography;
const { Option } = Select;

/** 分页大小选项 */
const PAGE_SIZE_OPTIONS = ['10', '20', '50'];

/** 性别选项映射 */
const GENDER_OPTIONS = [
    { value: '1', label: '男' },
    { value: '2', label: '女' }
] as const;

/** 前端性别选项 */
const FRONTEND_GENDER_OPTIONS = [
    { value: 'male', label: '男' },
    { value: 'female', label: '女' }
] as const;

/** 选项卡与审核状态映射 */
const TAB_STATUS_MAP: Record<string, string> = {
    reviewed: '3',  // 已审核
    pending: '2',    // 待审核
    rejected: '4'   // 已驳回
};

/** 日期格式化模板 */
const DATE_FORMAT = 'YYYY-MM-DD';
/** 搜索日期格式：仅年月（YYYY-MM） */
const SEARCH_DATE_FORMAT = 'YYYY-MM';

/** 出生日期限制 */
const DATE_LIMITS = {
    min: dayjs('1950-01-01', DATE_FORMAT),
    max: dayjs().subtract(20, 'year')
};

// 类型定义 

/**
 * 教师信息接口
 */
interface TeacherItem {
    id: number;           // 教师ID
    nickname: string;     // 教师姓名
    username: string;     // 用户名（手机号）
    avatar: string;       // 头像URL
    birthday: string | null; // 出生日期
    gender: string;       // 性别：1-男，2-女
    intr: string | null;  // 任职信息
    title: string;        // 班级名称
    squad_id: number;     // 班级ID
    age: number;         // 年龄
}

/**
 * 教师表单值接口
 */
interface TeacherFormValues {
    username?: string;    // 手机号
    nickname?: string;    // 姓名
    password?: string;    // 密码
    avatar?: string;      // 头像URL
    birthday?: dayjs.Dayjs; // 出生日期
    gender?: 'male' | 'female'; // 性别
    intr?: string;        // 任职信息
    squad_id?: string;    // 班级ID
}

/**
 * 搜索表单值接口
 */
interface SearchFormValues {
    nickname?: string;    // 教师姓名
    username?: string;    // 手机号
    title?: string;      // 班级名称
    gender?: string;     // 性别
    birthday?: dayjs.Dayjs | null; // 出生月份
    intr?: string;       // 任职信息
}

/**
 * 班级选项接口
 */
interface ClassOption {
    value: number;       // 班级ID
    label: string;       // 班级名称
}

/**
 * API响应接口
 */
interface ApiResponse<T = any> {
    code: number;        // 响应码
    data: T;            // 响应数据
    msg?: string;        // 响应消息
}

/**
 * 教师列表响应接口
 */
interface TeacherListResponse {
    list: TeacherItem[];        // 教师列表
    total: number;              // 总条数
    resolveTotal?: number;      // 已审核数量
    pendingTotal?: number;      // 待审核数量
    rejectTotal?: number;       // 已驳回数量
    squad?: ClassOption[];      // 班级选项
}

/**
 * 选项卡统计接口
 */
interface TabStats {
    resolved: number;   // 已审核数量
    pending: number;    // 待审核数量
    rejected: number;   // 已驳回数量
}

/**
 * 安全转换API响应
 * @param response API响应数据
 * @returns 标准化的API响应
 */
const safeConvertToApiResponse = <T,>(response: any): ApiResponse<T> => {
    if (response?.data?.code !== undefined) {
        return response.data;
    }
    if (response?.code !== undefined) {
        return response;
    }
    return {
        code: 0,
        data: {} as T,
        msg: '未知响应格式'
    };
};

/**
 * 转换性别为API格式
 * @param gender 前端性别值
 * @returns API性别值
 */
const convertGenderToApiFormat = (gender: string): string => {
    return gender === 'female' ? '2' : '1';
};

/**
 * 从API格式转换性别
 * @param gender API性别值
 * @returns 前端性别值
 */
const convertGenderFromApi = (gender: string): 'male' | 'female' => {
    return gender === '2' ? 'female' : 'male';
};

/**
 * 教师管理主组件
 */
const TeacherManagement: React.FC = () => {
    const { initialState } = useModel('@@initialState');

    // 状态管理 
    const [searchForm] = Form.useForm<SearchFormValues>();                    // 搜索表单实例
    const [teacherForm] = Form.useForm<TeacherFormValues>();                   // 教师表单实例

    // 教师列表数据
    const [teacherList, setTeacherList] = useState<TeacherItem[]>([]);
    // 加载状态
    const [loading, setLoading] = useState(false);
    // 模态框状态
    const [modalVisible, setModalVisible] = useState(false);                   // 模态框显示状态
    const [submitLoading, setSubmitLoading] = useState(false);                // 提交加载状态
    const [avatarUrl, setAvatarUrl] = useState('');                          // 头像URL
    const [currentEditId, setCurrentEditId] = useState<number | null>(null);  // 当前编辑ID
    const [activeTabKey, setActiveTabKey] = useState('reviewed');            // 当前激活的选项卡
    const [tabStats, setTabStats] = useState<TabStats>({ resolved: 0, pending: 0, rejected: 0 }); // 选项卡统计
    const [classOptions, setClassOptions] = useState<ClassOption[]>([]);     // 班级选项
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);  // 选中行keys

    // 引用
    const searchFormRef = useRef(searchForm);

    // 分页配置
    const [pagination, setPagination] = useState<TablePaginationConfig>({
        align: 'center',
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: (total) => `共 ${total} 条数据`,
        pageSizeOptions: PAGE_SIZE_OPTIONS,
    });

    // 数据获取函数 

    /**
     * 获取教师列表数据
     * @param params 请求参数
     */
    const getTeacherList = useCallback(async (params?: { current?: number; pageSize?: number }) => {
        setLoading(true);
        try {
            const searchValues = searchFormRef.current.getFieldsValue();
            const statusCode = TAB_STATUS_MAP[activeTabKey] || '';

            // 组装请求参数，过滤空值字段
            const requestParams = {
                current: params?.current || pagination.current || 1,
                pageSize: params?.pageSize || pagination.pageSize || 10,
                nickname: searchValues.nickname,
                username: searchValues.username,
                title: searchValues.title,
                gender: searchValues.gender,
                birthday: searchValues.birthday ? searchValues.birthday.format(SEARCH_DATE_FORMAT) : null,
                intr: searchValues.intr,
                audits: statusCode
            };

            // 过滤空值参数
            const filteredParams = Object.fromEntries(
                Object.entries(requestParams).filter(([_, value]) => value != null && value !== '')
            );

            // 调用API获取数据
            const response = await useListApi(filteredParams);
            // 转换API响应格式
            const apiResponse = safeConvertToApiResponse<TeacherListResponse>(response);

            if (apiResponse.code === 1) {
                const data = apiResponse.data || {};
                setTeacherList(data.list || []);
                const newPagination = {
                    ...pagination,
                    total: data.total || 0,
                    current: params?.current || pagination.current || 1,
                    pageSize: params?.pageSize || pagination.pageSize || 10,
                };

                setPagination(newPagination);

                // 更新选项卡统计
                setTabStats({
                    resolved: data.resolveTotal || 0,
                    pending: data.pendingTotal || 0,
                    rejected: data.rejectTotal || 0,
                });

                // 更新班级选项
                if (data.squad) {
                    setClassOptions(data.squad);
                }
            } else {
                message.error(apiResponse.msg || '获取数据失败');
            }
        } catch (error) {
            console.error('获取教师列表失败:', error);
            message.error('网络错误，获取教师列表失败');
        } finally {
            setLoading(false);
        }
    }, [activeTabKey, pagination]);

    // 事件处理函数 

    /**
     * 删除教师
     * @param ids 要删除的教师ID数组
     */
    const handleDelete = useCallback(async (ids: React.Key[]) => {
        try {
            const response = await useDeleteApi({ ids });
            const apiResponse = safeConvertToApiResponse(response);

            if (apiResponse.code === 1) {
                message.success(ids.length === 1 ? '删除成功' : '批量删除成功');
                setSelectedRowKeys(prev => prev.filter(key => !ids.includes(key)));
                getTeacherList();
            } else {
                message.error('删除失败：' + (apiResponse.msg || '未知错误'));
            }
        } catch (error) {
            console.error('删除教师失败:', error);
            message.error('删除失败');
        }
    }, [getTeacherList]);

    /**
     * 新增/编辑教师信息
     */
    const handleAddTeacher = useCallback(async () => {
        try {
            const values = await teacherForm.validateFields();
            setSubmitLoading(true);

            // 准备提交数据
            const submitData = {
                username: values.username || '',
                nickname: values.nickname || '',
                avatar: values.avatar || '',
                birthday: values.birthday ? values.birthday.format(DATE_FORMAT) : '',
                gender: convertGenderToApiFormat(values.gender || 'male'),
                intr: values.intr || '',
                squad_id: values.squad_id || '',
                ...(values.password && { password: values.password }),
                ...(currentEditId && { id: currentEditId })
            };

            const response = await useAddApi(submitData);
            const apiResponse = safeConvertToApiResponse(response);

            if (apiResponse.code === 1) {
                message.success(currentEditId ? '编辑教师成功' : '新增教师成功');
                handleCancelModal();
                getTeacherList();
            } else {
                message.error((apiResponse.msg || '操作失败'));
            }
        } catch (error: any) {
            console.error('操作教师失败:', error);
            if (error.errorFields) {
                const errorMessage = error.errorFields
                    .map((field: any) => field.errors.join(', '))
                    .join('; ');
                message.error(`表单验证失败: ${errorMessage}`);
            } else {
                message.error(currentEditId ? '编辑失败' : '新增失败');
            }
        } finally {
            setSubmitLoading(false);
        }
    }, [teacherForm, currentEditId, getTeacherList]);

    /**
     * 检查昵称或用户名是否重复
     * @param type 检查类型：nickname-姓名，username-手机号
     * @param value 要检查的值
     * @param excludeId 排除的ID（编辑时使用）
     * @returns 是否重复
     */
    const checkDuplicate = useCallback((type: 'nickname' | 'username', value: string, excludeId: number | null) => {
        if (!value) return false;
        return teacherList.some(item => {
            const fieldValue = type === 'nickname' ? item.nickname : item.username;
            return fieldValue === value && item.id !== excludeId;
        });
    }, [teacherList]);

    /**
     * 显示新增教师模态框
     */
    const handleShowModal = useCallback(() => {
        setModalVisible(true);
        setCurrentEditId(null);
        setAvatarUrl('');
        // 初始化表单默认值
        teacherForm.setFieldsValue({
            gender: 'male',
            avatar: '',
            password: ''
        });
    }, [teacherForm]);

    /**
     * 关闭模态框
     */
    const handleCancelModal = useCallback(() => {
        setModalVisible(false);
        teacherForm.resetFields();
        setAvatarUrl('');
        setCurrentEditId(null);
    }, [teacherForm]);

    /**
     * 图片上传成功回调
     * @param fullUrl 上传成功的图片URL
     */
    const handleImageUploadSuccess = useCallback((fullUrl: string | string[]) => {
        const url = Array.isArray(fullUrl) ? fullUrl[0] : fullUrl;
        setAvatarUrl(url);
        teacherForm.setFieldsValue({ avatar: url });
    }, [teacherForm]);

    /**
     * 编辑教师信息
     * @param record 要编辑的教师数据
     */
    const handleEdit = useCallback((record: TeacherItem) => {
        setCurrentEditId(record.id);
        setModalVisible(true);
        // 填充表单数据
        teacherForm.setFieldsValue({
            username: record.username,
            nickname: record.nickname,
            squad_id: record.squad_id?.toString(),
            intr: record.intr || '',
            gender: convertGenderFromApi(record.gender),
            avatar: record.avatar,
            birthday: record.birthday ? dayjs(record.birthday) : undefined,
            password: ''
        });
        setAvatarUrl(record.avatar);
    }, [teacherForm]);

    /**
     * 批量删除教师
     */
    const handleBatchDelete = useCallback(() => {
        if (selectedRowKeys.length === 0) {
            message.warning('请选择要删除的教师');
            return;
        }
        Modal.confirm({
            title: '是否确认批量删除？',
            content: `即将删除 ${selectedRowKeys.length} 条数据，删除后不可恢复，请谨慎操作`,
            okText: '确定',
            okType: 'danger',
            centered: true,
            cancelText: '取消',
            onOk: () => handleDelete(selectedRowKeys)
        });
    }, [selectedRowKeys, handleDelete]);

    /**
     * 处理表格分页变化
     * @param newPagination 新的分页配置
     */
    const handleTableChange = useCallback((newPagination: TablePaginationConfig) => {
        const updatedPagination = {
            ...pagination,
            current: newPagination.current || 1,
            pageSize: newPagination.pageSize || 10
        };

        setPagination(updatedPagination);
        setSelectedRowKeys([]);
        getTeacherList({
            current: updatedPagination.current,
            pageSize: updatedPagination.pageSize
        });
    }, [pagination, getTeacherList]);

    /**
     * 搜索处理函数
     */
    const handleSearch = useCallback(() => {
        setPagination(prev => ({ ...prev, current: 1 }));
        setSelectedRowKeys([]);
        getTeacherList({ current: 1 });
    }, [getTeacherList]);

    /**
     * 重置搜索条件
     */
    const handleReset = useCallback(() => {
        searchForm.resetFields();
        setPagination(prev => ({ ...prev, current: 1 }));
        setSelectedRowKeys([]);
        getTeacherList({ current: 1 });
    }, [searchForm, getTeacherList]);

    /**
     * 刷新列表
     */
    const handleRefresh = useCallback(() => {
        setSelectedRowKeys([]);
        getTeacherList();
    }, [getTeacherList]);

    /**
     * 切换标签页
     * @param tabKey 选项卡key
     */
    const handleTabChange = useCallback((tabKey: string) => {
        setPagination(prev => ({ ...prev, current: 1 }));
        setSelectedRowKeys([]);
        setActiveTabKey(tabKey);
    }, []);

    /**
     * 搜索框回车键处理函数
     * @param e 键盘事件
     */
    const handleInputKeyPress = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.key === 'Enter') {
            handleSearch();
        }
    }, [handleSearch]);

    // 表格配置 

    /**
     * 渲染性别文本
     * @param gender 性别值
     * @returns 性别显示文本
     */
    const renderGender = useCallback((gender: string) => {
        return gender === '1' ? '男' : gender === '2' ? '女' : '未设置';
    }, []);

    /**
     * 表格列配置
     */
    const columns: ColumnsType<TeacherItem> = useMemo(() => [
        {
            title: '序号',
            key: 'index',
            align: 'center',
            width: 80,
            render: (_, __, index) => {
                const current = pagination.current || 1;
                const pageSize = pagination.pageSize || 10;
                return (current - 1) * pageSize + index + 1;
            },
        },
        {
            title: '姓名',
            dataIndex: 'nickname',
            align: 'center',
            key: 'nickname',
        },
        {
            title: '电话',
            dataIndex: 'username',
            align: 'center',
            key: 'username',
        },
        {
            title: '班级',
            dataIndex: 'title',
            align: 'center',
            key: 'title',
            render: (title: string) => title || '无',
        },
        {
            title: '年龄',
            dataIndex: 'age',
            align: 'center',
            key: 'age',
            render: (age: number) => age || '暂无',
        },
        {
            title: '性别',
            dataIndex: 'gender',
            align: 'center',
            key: 'gender',
            width: 80,
            render: renderGender,
        },
        {
            title: '任职',
            dataIndex: 'intr',
            align: 'center',
            key: 'intr',
            render: (intr: string | null) => intr || '暂无',
        },
        {
            title: '头像',
            dataIndex: 'avatar',
            align: 'center',
            key: 'avatar',
            render: (avatar: string) =>
                avatar ? (
                    <Image
                        width={40}
                        height={40}
                        src={avatar}
                        style={{ objectFit: 'cover', borderRadius: '4px' }}
                        preview={{ minScale: 0.5, maxScale: 1.2, scaleStep: 0.1 }}
                    />
                ) : '无',
        },
        {
            title: '操作',
            key: 'action',
            width: 180,
            align: 'center',
            render: (_, record: TeacherItem) => (
                <Space size="small">
                    <Button
                        type="primary"
                        icon={<EditOutlined />}
                        className={styles.deleteButton}
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Popconfirm
                        title="是否确认删除？"
                        onConfirm={() => handleDelete([record.id])}
                        okText="确定"
                        cancelText="取消"
                        okType="danger"
                    >
                        <Button
                            type="primary"
                            danger
                            icon={<DeleteOutlined />}
                            className={styles.deleteButton}
                        >
                            删除
                        </Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ], [pagination.current, pagination.pageSize, renderGender, handleEdit, handleDelete]);

    /**
     * 表格行选择配置
     */
    const rowSelection = useMemo(() => ({
        selectedRowKeys,
        onChange: setSelectedRowKeys,
        columnWidth: 30,
    }), [selectedRowKeys]);

    // 渲染辅助函数 

    /**
     * 渲染选项卡内容
     * @returns 选项卡内容组件
     */
    const renderTabContent = useCallback(() => (
        <Card variant="borderless" styles={{ body: { padding: 0 } }}>
            <div className={styles.tabContent}>
                <div className={styles.actionBar}>
                    <div className={styles.actionButtons}>
                        <Space>
                            <Button
                                type="primary"
                                icon={<PlusOutlined />}
                                className={styles.deleteButton}
                                onClick={handleShowModal}
                            >
                                新建
                            </Button>
                            <Button
                                danger
                                icon={<DeleteOutlined />}
                                className={styles.deleteButton}
                                onClick={handleBatchDelete}
                                disabled={selectedRowKeys.length === 0}
                            >
                                批量删除
                            </Button>
                            <Button
                                icon={<DeleteOutlined />}
                                className={styles.deleteButton}
                            >
                                批量导入
                            </Button>
                            {activeTabKey === 'pending' && (
                                <>
                                    <Button
                                        type="primary"
                                        icon={<CheckOutlined />}
                                        className={styles.deleteButton}
                                    >
                                        批量通过
                                    </Button>
                                    <Button
                                        danger
                                        icon={<CloseOutlined />}
                                        className={styles.deleteButton}
                                    >
                                        批量驳回
                                    </Button>
                                </>
                            )}
                        </Space>
                    </div>
                    <div className={styles.refreshIcon}>
                        <RedoOutlined
                            style={{ fontSize: '18px', cursor: 'pointer' }}
                            className={loading ? styles.refreshing : ''}
                            title="刷新页面"
                            onClick={handleRefresh}
                        />
                    </div>
                </div>

                <Table
                    columns={columns}
                    dataSource={teacherList}
                    rowKey="id"
                    loading={loading}
                    className={styles.customTable}
                    pagination={pagination}
                    onChange={handleTableChange}
                    scroll={{ x: 'max-content' }}
                    rowSelection={rowSelection}
                />
            </div>
        </Card>
    ), [
        teacherList, loading, pagination, columns, rowSelection,
        handleTableChange, handleShowModal, handleBatchDelete,
        selectedRowKeys, activeTabKey, handleRefresh
    ]);

    /**
     * 选项卡项配置
     */
    const tabItems = useMemo(() => [
        {
            key: 'reviewed',
            label: `已审核(${tabStats.resolved})`,
            children: renderTabContent(),
        },
        {
            key: 'pending',
            label: `待审核(${tabStats.pending})`,
            children: renderTabContent(),
        },
        {
            key: 'rejected',
            label: `已驳回(${tabStats.rejected})`,
            children: renderTabContent(),
        },
    ], [tabStats, renderTabContent]);

    // 副作用 

    /**
     * 初始化加载数据
     */
    useEffect(() => {
        getTeacherList();
    }, []);

    /**
     * 选项卡切换时重新加载数据
     */
    useEffect(() => {
        if (activeTabKey) {
            getTeacherList({ current: 1 });
        }
    }, [activeTabKey]);

    // 组件渲染 
    return (
        <div className={styles.pageWrapper}>
            <Title level={4} className={styles.pageTitle}>教师管理</Title>

            {/* 搜索表单区域 */}
            <div className={styles.formContainer}>
                <Form
                    form={searchForm}
                    layout="inline"
                    colon={false}
                    labelAlign="left"
                    className={styles.formLeft}
                >
                    <Row gutter={[24, 16]} style={{ width: '100%', marginBottom: 16 }}>
                        <Col span={8}>
                            <Form.Item name="nickname" label="教师姓名" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
                                <Input placeholder="请输入教师姓名" onPressEnter={handleInputKeyPress} />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item name="username" label="教师电话" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
                                <Input placeholder="请输入教师电话" maxLength={11} onPressEnter={handleInputKeyPress} />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item name="title" label="班级名称" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
                                <Input placeholder="请输入班级名称" onPressEnter={handleInputKeyPress} />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={[24, 16]} style={{ width: '100%' }}>
                        <Col span={8}>
                            <Form.Item name="gender" label="性别" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
                                <Select
                                    placeholder="请选择性别"
                                    style={{ width: '100%' }}
                                    allowClear
                                    onChange={handleSearch}
                                    onClick={handleSearch}
                                >
                                    {GENDER_OPTIONS.map(option => (
                                        <Option key={option.value} value={option.value}>{option.label}</Option>
                                    ))}
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                name="birthday"
                                label="出生月份"
                                labelCol={{ span: 6 }}
                                wrapperCol={{ span: 18 }}
                            >
                                <DatePicker
                                    placeholder="请选择出生月份"
                                    style={{ width: '100%' }}
                                    format={SEARCH_DATE_FORMAT}
                                    onChange={handleSearch}
                                    onClick={handleSearch}
                                    minDate={DATE_LIMITS.min}
                                    maxDate={DATE_LIMITS.max}
                                    picker="month"
                                />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item name="intr" label="任职" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
                                <Input placeholder="请输入任职" onPressEnter={handleInputKeyPress} />
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>

                {/* 操作按钮区域 */}
                <div className={styles.formRight}>
                    <Button
                        type="primary"
                        icon={<SearchOutlined />}
                        className={styles.deleteButton}
                        onClick={handleSearch}
                        style={{ marginBottom: 8 }}
                    >
                        查询
                    </Button>
                    <Button
                        icon={<ReloadOutlined />}
                        className={styles.deleteButton}
                        onClick={handleReset}
                    >
                        重置
                    </Button>
                </div>
            </div>

            {/* 选项卡区域 */}
            <Tabs
                activeKey={activeTabKey}
                items={tabItems}
                onChange={handleTabChange}
                className={styles.tabsContainer}
                size="small"
                type="line"
            />

            {/* 新增/编辑教师模态框 */}
            <Modal
                title={currentEditId ? '编辑教师' : '新建教师'}
                open={modalVisible}
                onCancel={handleCancelModal}
                className={styles.modalContainer}
                centered
                footer={[
                    <Button key="cancel" onClick={handleCancelModal}>取消</Button>,
                    <Button key="submit" type="primary" loading={submitLoading} onClick={handleAddTeacher}>
                        确定
                    </Button>,
                ]}
                maskClosable={false}
                width={540}
            >
                <Form
                    form={teacherForm}
                    layout="horizontal"
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 19 }}
                    style={{ minHeight: '400px' }}
                >
                    {/* 手机号表单项 */}
                    <Form.Item
                        name="username"
                        label="手机号"
                        rules={[
                            { required: true, message: '请输入手机号' },
                            {
                                validator: async (_, value) => {
                                    if (value && checkDuplicate('username', value, currentEditId)) {
                                        throw new Error('该手机号已存在，请更换');
                                    }
                                },
                            },
                        ]}
                    >
                        <Input
                            placeholder="请输入手机号"
                            maxLength={11}
                            onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                                handleNumberInput(teacherForm, 'username', e, { supportDecimal: false })
                            }
                            onInput={(e: React.ChangeEvent<HTMLInputElement>) =>
                                handleNumberInput(teacherForm, 'username', e, { supportDecimal: false })
                            }
                        />
                    </Form.Item>

                    {/* 密码表单项 */}
                    <Form.Item
                        name="password"
                        label="密码"
                        rules={[
                            { required: !currentEditId, message: '请输入密码' },
                            { min: 6, message: '密码长度不能少于6位' },
                            { max: 20, message: '密码长度不能超过20位' },
                        ]}
                    >
                        <Input.Password
                            placeholder={currentEditId ? '不修改请留空' : '请输入密码'}
                            onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                                handlePasswordInput(teacherForm, 'password', e)
                            }
                            onInput={(e: React.ChangeEvent<HTMLInputElement>) =>
                                handlePasswordInput(teacherForm, 'password', e)
                            }
                        />
                    </Form.Item>
                    {/* 班级选择表单项 */}
                    <Form.Item name="squad_id" label="班级" rules={[{ required: true, message: '请选择班级' }]}>
                        <Select placeholder="请选择班级" allowClear>
                            {classOptions.map(option => (
                                <Select.Option key={option.value} value={option.value.toString()}>
                                    {option.label}
                                </Select.Option>
                            ))}
                        </Select>
                    </Form.Item>

                    {/* 任职表单项 */}
                    <Form.Item
                        name="intr"
                        label="任职"
                        rules={[
                            { required: true, message: '请输入任职' },
                            { max: 10, message: '任职名称不能超过10个字符' }
                        ]}
                    >
                        <Input
                            placeholder="请输入任职"
                            onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                                handleTextOnlyInput(teacherForm, 'intr', e, { maxLength: 10 })
                            }
                            onInput={(e: React.ChangeEvent<HTMLInputElement>) =>
                                handleTextOnlyInput(teacherForm, 'intr', e, { maxLength: 10 })
                            }
                        />
                    </Form.Item>

                    {/* 姓名表单项 */}
                    <Form.Item name="nickname" label="姓名" rules={[
                        { required: true, message: '请输入姓名' },
                        { max: 10, message: '姓名长度不能超过10位' },
                        {
                            validator: async (_, value) => {
                                if (checkDuplicate('nickname', value || '', currentEditId)) {
                                    throw new Error('该姓名已存在，请更换');
                                }
                            },
                        },
                    ]}>
                        <Input
                            placeholder="请输入姓名"
                            onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                                handleTextOnlyInput(teacherForm, 'nickname', e, { maxLength: 10 })
                            }
                            onInput={(e: React.ChangeEvent<HTMLInputElement>) =>
                                handleTextOnlyInput(teacherForm, 'nickname', e, { maxLength: 10 })
                            }

                        />
                    </Form.Item>

                    {/* 性别表单项 */}
                    <Form.Item name="gender" label="性别" rules={[{ required: true, message: '请选择性别' }]}>
                        <Radio.Group>
                            {FRONTEND_GENDER_OPTIONS.map(option => (
                                <Radio key={option.value} value={option.value}>{option.label}</Radio>
                            ))}
                        </Radio.Group>
                    </Form.Item>

                    {/* 照片表单项 */}
                    <Form.Item name="avatar" label="照片" rules={[{ required: true, message: '请上传照片' }]}>
                        <ImageUploader
                            key={avatarUrl}
                            imageUrl={avatarUrl}
                            onUploadSuccess={handleImageUploadSuccess}
                            accept="image/*"
                            maxCount={1}
                        />
                    </Form.Item>

                    {/* 出生日期表单项 */}
                    <Form.Item name="birthday" label="出生日期" rules={[{ required: true, message: '请选择出生日期' }]}>
                        <DatePicker
                            placeholder="请选择出生日期"
                            style={{ width: '100%' }}
                            minDate={DATE_LIMITS.min}
                            maxDate={DATE_LIMITS.max}
                            format={DATE_FORMAT}
                        />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default TeacherManagement;